package cn.tao.org.service.impl;

import cn.tao.base.service.impl.BaseServiceImpl;
import cn.tao.org.domain.Department;
import cn.tao.org.mapper.DepartmentMapper;
import cn.tao.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;

    @Override
    @Transactional
    public void save(Department department) {
        //先保存，获取到返回的id
        departmentMapper.save(department);

        update(department);
    }

    @Override
    @Transactional
    public void delete(Long id) {
        departmentMapper.delete(id);
    }

    @Override
    @Transactional
    public void update(Department department) {
        //维护dirpath,判断parent_id是否为空，,因为sql中parent_id被parts.id代替，确定是不是第一级
        if (department.getParts() ==null){
            //为空，直接拼接自己的id
            department.setDirPath("/"+department.getId());
        }else {
            //不为空，就找到上一级部门数据，获取他的dirpath再拼接，因为parts就是一个department对象
            Department parts = department.getParts();//此时拿出来的只封装了id

            Department parts1 = departmentMapper.loadById(parts.getId());
            department.setDirPath(parts1.getDirPath()+"/"+department.getId());

        }
        departmentMapper.update(department);
    }

    /**
     * 批量删除，接收一个long类型的数组
     * @param ids
     */
    @Override
    @Transactional
    public void batchDelete(Long[] ids) {
        departmentMapper.batchDelete(ids);
    }

    /**
     * 上级部门多级展示
     * @return
     */

    public List<Department> loadDeptTree() {
        return departmentMapper.loadDeptTree();
    }
}
